package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.jwm.power.mapper.OperateMapper;
import com.jwm.power.model.common.EnumMenu;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.*;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.*;
import com.jwm.power.service.UsersService;
import com.jwm.power.util.FileUtil;
import com.jwm.power.util.Ut;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service("usersService")
@Transactional
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private OperateMapper operateMapper;
    @Autowired
    private JobsRepository jobsRepository;
    @Autowired
    private DeptsRepository deptsRepository;
    @Autowired
    private FormcustomsRepository formcustomsRepository;

    //  用户登录
    @Override
    public ResponseData UserLogin(HttpServletRequest request) {
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        try {

            Users users = usersRepository.findByUsernameAndUserpassword(userName, passWord);
            if (users == null) {
                return new ResponseData(EnumResult.USER_FAIL, null);
            }
            StpUtil.login(users.getUserid());
            StpUtil.getSession().set("users", users);
            //  添加日志
            Logs log = Ut.SaveLog("login", "", null, users);
            logsRepository.save(log);
            Deptjob deptjob = jobsRepository.findByJobcode(users.getJobcode());
            String jobname = users.getUsername().equals("admin") ? "超级管理员" : deptjob != null ? deptjob.getJobname() : "暂无";
            Depts depts = deptsRepository.findByDeptcode(users.getDeptcode());
            //  返回用户数据
            Map<String, Object> uMap = new HashMap<>();
            uMap.put("name", users.getName());
            uMap.put("imgurl", users.getImgurl());
            uMap.put("jobname", jobname);
            uMap.put("deptname", depts != null ? depts.getDeptname() : "暂无");
            uMap.put("userAuth", StpUtil.getPermissionList());
            uMap.put("cusType",users.getCustomerType());

            return new ResponseData(EnumResult.SUCCESS, Ut.toJson(uMap));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  获取用户
    @Override
    public ResponseData GetUsers(HttpServletRequest request) {
        Users users = (Users) StpUtil.getSession().get("users");
        try {
            Users model = usersRepository.findByUserid(users.getUserid());
            return new ResponseData(EnumResult.SUCCESS, model);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置用户
    @Override
    public ResponseData SaveUsers(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            Users model_New = new Users();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);

            Integer operationType = 0;
            if (model_New.getUserid() != null && model_New.getUserid() > 0) {
                operationType = 1;
                //  检查用户名是否存在
                Users checkUser = usersRepository.findByUsernameAndUseridNot(model_New.getUsername(), model_New.getUserid());
                if (checkUser != null) {
                    return new ResponseData(EnumResult.USER_FAIL_NAME, null);
                }
            } else {
                //  检查用户名是否存在
                Users checkUser = usersRepository.findByUsernameAndUseridNot(model_New.getUsername(), 0);
                if (checkUser != null) {
                    return new ResponseData(EnumResult.USER_FAIL_NAME, null);
                }
            }

            usersRepository.save(model_New);

            //  添加日志
            Logs log = Ut.SaveLog("users", model_New.getName(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置用户
    @Override
    public ResponseData SaveUsersInfo(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            Users model_New = new Users();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);

            if (model_New.getUserid() != null && model_New.getUserid() > 0) {
                //  检查用户名是否存在
                Users checkUser = usersRepository.findByUsernameAndUseridNot(model_New.getUsername(), model_New.getUserid());
                if (checkUser != null) {
                    return new ResponseData(EnumResult.USER_FAIL_NAME, null);
                }
            }

            usersRepository.save(model_New);

            StpUtil.getSession().set("users", model_New);
            //  添加日志
            Logs log = Ut.SaveLog("usersInfo", model_New.getName(), EnumOperate.EDIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置用户部门数据权限
    @Override
    public ResponseData SaveUserDepts(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            String moduleItems = request.getParameter("moduleItems");//菜单编码集合
            String userId = request.getParameter("userId");//用户ID
            Map<String, Object> map = new HashMap<>();
            map.put("tName", "UserDepts");
            map.put("strWhere", "UserID ='" + userId + "'");
            operateMapper.deleteDefined(map);   //  删除原有权限
            //  添加新权限
            map = new HashMap<>();
            map.put("depts", moduleItems.split(","));
            map.put("userId", userId);
            operateMapper.insertBatchUserDepts(map);   //  批量增加职务权限
            //  添加日志
            Logs log = Ut.SaveLog("userDepts", moduleItems, EnumOperate.EDIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置用户菜单数据权限
    @Override
    public ResponseData SaveUserMenus(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            String moduleItems = request.getParameter("moduleItems");//菜单编码集合
            String userId = request.getParameter("userId");//用户ID
            Map<String, Object> map = new HashMap<>();
            map.put("tName", "UserMenus");
            map.put("strWhere", "UserID ='" + userId + "'");
            operateMapper.deleteDefined(map);   //  删除原有权限
            //  添加新权限
            map = new HashMap<>();
            map.put("menus", moduleItems.split(","));
            map.put("userId", userId);
            operateMapper.insertBatchUserMenus(map);   //  批量增加职务权限
            //  添加日志
            Logs log = Ut.SaveLog("userMenus", moduleItems, EnumOperate.EDIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  设置用户头像
    @Override
    public String SaveUserImg(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            ModelAndView mv = new ModelAndView();
            mv.setViewName("result");
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = mr.getFile("photoimg");

            String fileName = FileUtil.uploadFiles(multipartFile, 0, 0);

            //  添加日志
            Logs log = Ut.SaveLog("userImg", fileName, EnumOperate.EDIT, users);
            logsRepository.save(log);
            return "|success|" + fileName + "|";
        } catch (Exception e) {
            e.printStackTrace();
            return "|fail|" + e.getMessage() + "|";
        }
    }


    //  设置自定义表单
    @Override
    public ResponseData SaveFormCustoms(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            Formcustoms model_New = new Formcustoms();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            model_New.setSn(0);
            if (model_New.getFid() != null && model_New.getFid() > 0) {

            } else {
                String maxCode = formcustomsRepository.getMaxCode(model_New.getModulename());
                maxCode = maxCode != null ? maxCode : "0000";
                model_New.setFcode(String.format("%04d", Integer.parseInt(maxCode) + 1));
            }
            formcustomsRepository.save(model_New);
            //  添加日志
            Logs log = Ut.SaveLog("formCustoms", model_New.getFname(), EnumOperate.EDIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
}
